<template>
  <ForOneHeader :showLeft="false" :is_show="is_show_header"/>
  <div class="index-container">
    <u-swiper indicator keyName="image" circular class="index-swiper" :list="bannerStore.bannerList" @click="onclick"
      height="850rpx">
      
    </u-swiper>
    <CategorySection :categoryList="categoryList"/>
    
   
    <view style="position: relative;top: -20rpx;">
      <VideoCenter :random_video_list_channel="random_video_list_channel" :random_channel="random_channel" />
    

    <PdfList :color_atlas_category="color_atlas_category" />
    <Download v-if="download_categories.length > 0" :download_categories="download_categories"/>
    <UnionSection :unionList="unionList" @updateUnions="handleUpdateUnions" />
    <Intros :image="intros_image" />
    <SpaceSection :indexCaseList="indexCases"/>
    </view>
  </div>
</template>

<script setup lang="ts">
import CategorySection from './category-section.vue'
import UnionSection from './union-section.vue'
import SpaceSection from './space-section.vue'
import VideoCenter from './video-center.vue'
import PdfList from './pdf-list.vue'
import Download from './download.vue'
import Intros from './intros.vue'
import { useBannerStore } from '@/store/banner'
import { useAppConfigStore } from '@/store/appconfig'
import { useSettingStore } from '@/store/setting'

import {getDistFromStore} from '@/api/index'
const bannerStore = useBannerStore()
const appConfigStore = useAppConfigStore()
const settingStore =  useSettingStore()
import { ref, onBeforeMount,watch} from 'vue'
import {  onShareTimeline,onShareAppMessage,onPageScroll, onShow } from "@dcloudio/uni-app";
import {shareUtils} from '@/utils/share'
import useShare from '@/mixins/share'
const unionList = ref([])
const categoryList = ref([])
const indexCases = ref([])
const intros_image = ref(null)
const random_channel = ref({})
const download_categories = ref([])
const random_video_list_channel = ref({})
const color_atlas_category = ref([])
const is_show_header = ref(false)
const {getShareCover} = useShare()
const inited = ref(false)

onPageScroll((e)=>{

  const s = e.scrollTop

  is_show_header.value = s > 200
})
const handleUpdateUnions = (res)=>{
  unionList.value = res
}

const dist_to_float = (dist) => {
  return parseFloat(dist).toFixed(1)
}


watch(() => [settingStore.nearest_store], ([ newDist],[oldDist]) => {

  const r = newDist.value;

  const r_map = {};

  r.forEach(el => {
    r_map[el[0]] = el[1]
  })


  // debugger
  if (r_map != {}) {
    // debugger
    let a = unionList.value.map(el => {

      el.dist = dist_to_float(r_map[el.id])
      console.log(el.dist)
      return el
    }).sort((a, b) => {
      return a.dist - b.dist
    })

    console.log(a)
    unionList.value = a 

  }



}, { deep: true })

const onclick = (e) => {
  const target = bannerStore.bannerList[e]

  const { open_type, open_type_config } = target.my_open_type

  if (open_type == 'official_account') {
    wx.openOfficialAccountArticle({
      url: open_type_config.official_account_url,
      success: res => {

      },
      fail: res => {
      }
    })
  }


  if (open_type == 'mini_program') {
    wx.navigateTo({
      url: open_type_config.mini_program_path,
      success: res => {

        debugger
      },
      fail: res => {

        debugger
      }
    })
  }

}




const page = getCurrentPages().pop()
let path: string = page.route

const share_path = shareUtils.buildPathQuery(path)
onShareAppMessage(() => {

  const promise = new Promise(resolve => {
    getShareCover(path, null, null).then(res => {

      res.path = share_path

      resolve(res)

    })
  })

  return {
    path: share_path,
    imageUrl: null,
    promise
  }
})



onShareTimeline(() => {

  const promise = new Promise(resolve => {
    getShareCover(path, null, null).then(res => {

      res.path = share_path

      // debugger
      resolve(res)

    })
  })

  return {
    path: share_path,
    imageUrl: null,
    promise
  }
})
const getLocation = ()=>{

    return new Promise((resolve)=>{
      wx.getLocation({
      type: 'wgs84',
      success(res) {
        const latitude = res.latitude
        const longitude = res.longitude
        const speed = res.speed
        const accuracy = res.accuracy
        getDistFromStore({
          lng:longitude,
          lat:latitude
        }).then(res=>{
         
          if(res){
            
            settingStore.nearest_store.value = res
            resolve(true)
          }
        })
      },
      fail(res){

        console.error(res)
        uni.showModal({
          title:JSON.stringify(res)
        })
        // debugger
      }
    })
    })
    
  }

const init = ()=>{
  inited.value = true;
  bannerStore.initBannerListByStore()
  appConfigStore.getConfig()
  settingStore.initSettingListByStore().then(res=>{
    
    indexCases.value = res.indexCases
    
    categoryList.value= res.routes
    intros_image.value = res.sys_config.company_intros_banner
    random_video_list_channel.value = res.random_video_list_channel
    random_channel.value = res.random_channel
    unionList.value = res.businessPartner
    download_categories.value=res.download_categories
    color_atlas_category.value = res.color_atlas_category
    wx.getSetting({
    success(res) {
      if (!res.authSetting['scope.userLocation']) {
        wx.authorize({
          scope: 'scope.userLocation',
          success() {
            getLocation().then(()=>{
              setUnions()
            })
          }
        })
      } else {
        getLocation().then(()=>{
          setUnions()
        })
      }

     

    }
  })

    
    
  })
}

const setUnions = ()=>{
  if(settingStore.nearest_store.value ){
      let dist_sort = settingStore.nearest_store.value
      
      const r_map = {};

      dist_sort.forEach(el => {
        r_map[el[0]] = el[1]
      })
      unionList.value = unionList.value.map(el=>{
        el.dist = dist_to_float(r_map[el.id])
      
      return el
      }).sort((a, b) => {
        return a.dist - b.dist
      })
    }
}
onBeforeMount(() => {
  
  !inited.value && init()
})

onShow(()=>{
  !inited.value && init()
})


</script>

<style lang="scss" scoped>

.index-container{

}


</style>
